<template>
  <div class="app-container">
    <el-descriptions :column="3" title="个人信息" border>
      <template #extra>
        <el-button type="primary" @click="handleShowUpdateUserInfoDialog">修改信息</el-button>
      </template>

      <el-descriptions-item label="姓名">{{ userInfo.name }}</el-descriptions-item>
      <el-descriptions-item label="性别">{{ userInfo.sex | sexFilter }}</el-descriptions-item>
      <el-descriptions-item label="头像">
        <el-image :src="userInfo.avatarUrl" style="width:78px;height:118px;" alt="" />
      </el-descriptions-item>

      <el-descriptions-item label="学号">{{ userInfo.id }}</el-descriptions-item>
      <el-descriptions-item label="学院" :span="2">{{ userInfo.collegeName }}</el-descriptions-item>

      <el-descriptions-item label="身份证号">{{ userInfo.card }}</el-descriptions-item>
      <el-descriptions-item label="手机号" :span="2">{{ userInfo.phone }}</el-descriptions-item>

      <el-descriptions-item label="居住地址">{{ userInfo.address }}</el-descriptions-item>
    </el-descriptions>

    <el-dialog
      title="修改个人信息"
      :visible.sync="showDialog"
      :append-to-body="true"
      @close="showDialog = false"
    >
      <el-form ref="updateUserInfo" label-width="80px" :model="updateUserInfo" :rules="rules">
        <el-form-item label="头像" prop="avatarUrl">
          <el-upload
            class="avatar-uploader"
            :on-change="uploadAvatar"
            :show-file-list="false"
            :auto-upload="false"
            action="#"
          >
            <img v-if="updateUserInfo.avatarUrl" :src="updateUserInfo.avatarUrl" class="avatar" alt="">
            <i v-else class="el-icon-plus avatarUrl-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="身份证号" prop="card">
          <el-input
            ref="card"
            v-model="updateUserInfo.card"
            placeholder="请输入身份证号"
            type="text"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            ref="phone"
            v-model="updateUserInfo.phone"
            placeholder="请输入手机号"
            type="text"
          />
        </el-form-item>
        <el-form-item label="居住地址" prop="address">
          <el-input
            ref="address"
            v-model="updateUserInfo.address"
            placeholder="请输入居住地址"
            type="textarea"
            autosize
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleUpdateUserInfo()">确认修改</el-button>
          <el-button @click="showDialog = false">取消修改</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { sexMap } from '@/constant/filterMap'
import { cardPattern, phonePattern } from '@/utils/validate'
import { getUserInfo, updateUserInfo } from '@/api/info'

export default {
  name: 'Info',
  filters: {
    sexFilter(sex) {
      return sexMap[sex]
    }
  },
  data() {
    return {
      userInfo: {
        id: '',
        name: '',
        collegeName: '',
        sex: '',
        avatarUrl: '',
        phone: '',
        card: '',
        address: ''
      },
      rules: {
        card: [{ pattern: cardPattern, message: '身份证格式错误', trigger: 'blur' }],
        phone: [{ pattern: phonePattern, message: '手机号格式错误', trigger: 'blur' }]
      },
      updateUserInfo: {},
      showDialog: false
    }
  },
  computed: {
    ...mapGetters([
      'id',
      'role'
    ])
  },
  created() {
    this.getUserInfo()
  },
  methods: {
    /**
     * 获取个人详细信息
     */
    async getUserInfo() {
      this.userInfo = await getUserInfo(this.id, this.role)
    },
    /**
     * 显示修改个人详细信息对话框
     */
    handleShowUpdateUserInfoDialog() {
      this.updateUserInfo = { ...this.userInfo }
      this.$nextTick(() => {
        this.showDialog = true
      })
    },
    /**
     * 上传头像
     * @param uploadAvatar
     */
    uploadAvatar(uploadAvatar) {
      // 图片是否为jpg和jpeg格式
      if (uploadAvatar.raw.type !== 'image/jpeg') {
        this.$message.error('上传头像图片只能是 JPG 格式!')
        return
      }
      // 图片大小是否大于2M
      if (!(uploadAvatar.size / 1024 / 1024 < 2)) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return
      }

      // 生成图片的临时路径预览图片
      this.updateUserInfo.avatarUrl = URL.createObjectURL(uploadAvatar.raw)
      this.updateUserInfo.avatarFile = uploadAvatar.raw
    },
    /**
     * 修改个人详细信息
     */
    handleUpdateUserInfo() {
      this.$refs.updateUserInfo.validate(async valid => {
        if (valid) {
          // 没有修改头像就不上传
          if (this.userInfo.avatarUrl === this.updateUserInfo.avatarUrl) {
            this.$delete(this.updateUserInfo, 'avatarFile')
          }

          // 将普通对象转换成FormData对象
          const formData = new FormData()
          for (const key in this.updateUserInfo) {
            formData.append(key, this.updateUserInfo[key])
          }
          await updateUserInfo(formData, this.role)

          this.showDialog = false
          this.$message.success('修改个人信息成功')
          await this.getUserInfo()
        }
      })
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
